package itsm.isperp.framework.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UploadInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import audio.AudioAttributes;
import audio.Encoder;
import audio.EncodingAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-31
 * @since 1.0
 * 
 */
public class FileUploadUtils {

	public static final Logger logger = LoggerFactory
			.getLogger(FileUploadUtils.class);

	private static final String FILENAME_DATEPART_FORMAT = "yyyyMM";

	public static final File persist(final InputStream inputStream,
			UploadInfo uploadInfo) throws IOException {

		String yyyyMM = DateFormatUtils.format(new Date(),
				FILENAME_DATEPART_FORMAT);
		File destFile = createFile(uploadInfo, yyyyMM);

		OutputStream outputStream = null;
		try {

			String filePath = ContextHolder.getUploadFileStore() + yyyyMM + "/"
					+ destFile.getName();
			uploadInfo.setPath(filePath);
			logger.info("uploadInfo path:" + filePath);
			outputStream = FileUtils.openOutputStream(destFile);
			IOUtils.copy(inputStream, outputStream);
		} finally {
			IOUtils.closeQuietly(outputStream);
		}

		return destFile;
	}

	/**
	 * 创建文件
	 * 
	 * @param uploadInfo
	 * @param yyyyMM
	 * @return
	 * @throws IOException
	 */
	public static final File createFile(final UploadInfo uploadInfo,
			final String yyyyMM) throws IOException {

		String fileStore = ContextHolder.getUploadFileStorePath() + "/"
				+ yyyyMM;
		
	  
		File file = new File(fileStore);
		logger.info("uploadInfo fileStore:" + fileStore);
		if (!file.exists()) {
			file.mkdirs();
		}

		String fileName = uploadInfo.getId() + "." + uploadInfo.getExt();
		logger.info("uploadInfo fileName:" + fileName);
		File destFile = new File(file, fileName);
		boolean newFileCreated = destFile.createNewFile();
		if (!newFileCreated) {
			throw new RuntimeException(String.format("未能成功创建文件[%s]",
					destFile.getAbsolutePath()));
		}

		return destFile;

	}

	/**
	 * 持久化输入流到文件中
	 * 
	 * @param inputStream
	 * @param name
	 * @param downloadType
	 * @return
	 * @throws IOException
	 */
	public static final UploadInfo persist(final File sourceFile,
			String fileNameExt, String msgTypeName) throws IOException {

		UploadInfo uploadInfo = uploadInfo(msgTypeName);

		uploadInfo.setExt(fileNameExt);
		uploadInfo.setPath(sourceFile.getPath());
		uploadInfo.setSize(new FileInputStream(sourceFile).available());

		if ("amr".equals(fileNameExt)) {
			File targetFile = new File(sourceFile.getParent() + "/"
					+ uploadInfo.getId() + ".mp3");

			AudioAttributes audio = new AudioAttributes();
			Encoder encoder = new Encoder();

			// pcm_s16le libmp3lame libvorbis libfaac
			audio.setCodec("libmp3lame");
			EncodingAttributes attrs = new EncodingAttributes();
			attrs.setFormat("mp3");
			attrs.setAudioAttributes(audio);

			uploadInfo.setPath(uploadInfo.getPath().replace(".amr", ".mp3"));
			uploadInfo.setExt("mp3");
			uploadInfo.setContentType("audio/mpeg");

			try {
				encoder.encode(sourceFile, targetFile, attrs);
				persist(new FileInputStream(targetFile), uploadInfo);
				return uploadInfo;
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		persist(new FileInputStream(sourceFile), uploadInfo);

		return uploadInfo;
	}

	/**
	 * 构造文件上传信息类
	 * 
	 * @param name
	 * @return
	 */
	public static final UploadInfo uploadInfo(final String name) {
		UploadInfo uploadInfo = ContextHolder
				.getSpringBean("isperp.uploadInfo");
		uploadInfo.setId(HibernateUUIDGenerator.generate());
		uploadInfo.setContentType("image/pjpeg");
		uploadInfo.setName(name);
		return uploadInfo;
	}
}
